/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package apprendomnumber;

import db.DatabaseConnection2;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
import util.RandomNumber;

/**
 *
 * @author phat10130059
 */
public class App extends javax.swing.JFrame {

    /**
     * Creates new form App
     */
    private DatabaseConnection2 db2 = new DatabaseConnection2();

    public App() {
        initComponents();

        

        setResizable(false);
        setSize(400, 100);
        setLocationRelativeTo(null);
        this.setIconImage(new javax.swing.ImageIcon(getClass().getResource("/img/icon.png")).getImage());
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        txtCode = new javax.swing.JTextField();
        jPanel1 = new javax.swing.JPanel();
        btGenerate = new javax.swing.JButton();
        btAccept = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Tool generate code");
        getContentPane().setLayout(new java.awt.GridLayout(2, 1));

        txtCode.setEditable(false);
        txtCode.setForeground(new java.awt.Color(51, 0, 204));
        txtCode.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        getContentPane().add(txtCode);

        btGenerate.setText("Generate");
        btGenerate.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btGenerateActionPerformed(evt);
            }
        });

        btAccept.setText("Accept");
        btAccept.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btAcceptActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(90, 90, 90)
                .addComponent(btGenerate)
                .addGap(66, 66, 66)
                .addComponent(btAccept)
                .addContainerGap(102, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btGenerate)
                    .addComponent(btAccept))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        getContentPane().add(jPanel1);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btGenerateActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btGenerateActionPerformed
        String number10 = RandomNumber.number10();
        txtCode.setText(number10);
    }//GEN-LAST:event_btGenerateActionPerformed

    private void btAcceptActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btAcceptActionPerformed
        
        
        
        boolean insert = false;


        if (!txtCode.getText().equals("")) {

            if (checkExist()) {
                
                db2.makeConnection();
                
                try {
                    String sqlInsert = "INSERT INTO license "
                            + " (code, seri_hard_disk)"
                            + " VALUES ( ? , ? ) ";
                    System.out.println(sqlInsert);
                    insert = db2.executeUpdate(sqlInsert, new String[]{txtCode.getText(), ""});


                } catch (Exception ex) {
                    ex.printStackTrace();
                } finally {
                    db2.closeConnection();
                }

                if (insert) {

                    JOptionPane.showMessageDialog(this, "Success", null, JOptionPane.INFORMATION_MESSAGE);

                } else {
                    JOptionPane.showMessageDialog(this, "Error", null, JOptionPane.ERROR_MESSAGE);
                }
            }else{
                JOptionPane.showMessageDialog(this, "Code exist!", null, JOptionPane.ERROR_MESSAGE);
            }

        }

    }//GEN-LAST:event_btAcceptActionPerformed

    private boolean checkExist() {
        
        db2.makeConnection();

        try {
            String sql = "select * from license where code = ? ";

            ResultSet rs = db2.executeQuery(sql, new String[]{txtCode.getText()});

            if (!rs.next()) {
                return true;
            }

        } catch (SQLException ex) {
            ex.printStackTrace();
        } finally {
            db2.closeConnection();
        }


        return false;

    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (Exception e) {
            e.printStackTrace();
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new App().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btAccept;
    private javax.swing.JButton btGenerate;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JTextField txtCode;
    // End of variables declaration//GEN-END:variables
}
